/* eslint-disable @typescript-eslint/no-unused-vars */
/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { defineStore } from 'pinia'
import { TabRouteConfig, TabRouteState } from './types'

export const useTabsRouteStore = defineStore({
  id: 'tabsRoute',
  state: (): TabRouteState => ({
    routers: [],
    dbIds: []
  }),
  getters: {
    getAllRoutes(): any {
      return this.routers
    },
    getDbIds(): string[] {
      return this.dbIds
    }
  },
  actions: {
    addTabRoute(route: any): void {
      // put new tab id into state.dbIds
      this.dbIds.indexOf(route.params.dbId) === -1 &&
        this.dbIds.push(route.params.dbId)
      const duplicate = this.routers.some((item: TabRouteConfig) => {
        return item.path === route.path
      })
      if (!duplicate) {
        const newRoute = {
          name: route.name,
          path: route.path,
          query: route.query,
          label: route.name
        }
        this.routers.push(newRoute)
      }
    },
    deleteRoute(name: string): void {
      const _routers = this.routers.filter((item: TabRouteConfig) => {
        return item.path !== '/explore/sqlconsole/' + name
      })
      this.routers = _routers
      const index = this.dbIds.indexOf(name)
      // eslint-disable-next-line no-unused-vars
      const { [index]: item, ...rest } = this.dbIds
      this.dbIds = Object.values(rest)
    },
    clearRoute(state: TabRouteState) {
      state.dbIds = []
      state.routers = []
    }
  }
})
